package com.ruge._05_springboot_web.controller;

import com.ruge._05_springboot_web.config.async.AsyncTask;
import com.ruge._05_springboot_web.config.exception.MyException;
import com.ruge._05_springboot_web.model.JsonPersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

@RestController
public class JsonController {
    @Autowired
    private AsyncTask asyncTask;

    @RequestMapping("user")
    public Map<String, Object> list() {
        Map<String, Object> map = new HashMap<>();
        JsonPersion persion = new JsonPersion();
        persion.setId(1);
        persion.setName("张三");
        persion.setDate(new Date());
        map.put("user", persion);
        int y = 1 / 0;
        return map;
    }


    @RequestMapping("async")
    public Map<String, Object> async() throws Exception {
        long start = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        Future<String> task1 = asyncTask.task1();
        Future<String> task2 = asyncTask.task2();
        Future<String> task3 = asyncTask.task3();
        while (true) {
            if (task1.isDone() && task2.isDone() && task3.isDone()) {
                break;
            }
            Thread.sleep(100);
        }
        long end = System.currentTimeMillis();
        map.put("task1",task1.get());
        map.put("task2",task2.get());
        map.put("task3",task3.get());
        map.put("总耗时",end-start);
        return map;
    }
}
